#include "EpollServer.hpp"
#include <memory>

protocol_ns::Response CalculateHelper(const protocol_ns::Request &req)
{
    // 走到这里，一定保证req是有具体数据的！
    // _result(result), _code(code)
    protocol_ns::Response resp(0, 0);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;
        break;
    case '*':
        resp._result = req._x * req._y;
        break;
    case '/':
        if (req._y == 0)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if (req._y == 0)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 3;
        break;
    }

    return resp;
}

void Calculate(Connection * conn, const protocol_ns::Request &req)
{
    protocol_ns::Response resp = CalculateHelper(req);
    std::string respStr;
    resp.Serialize(&respStr);
    respStr = protocol_ns::AddHeader(respStr);

    conn->_outbuffer += respStr;
    conn->R->EnableReadWrite(conn, true, true);
    LogMessage(Info, "Calculate success...");
}

int main()
{
    std::unique_ptr<EpollServer> server(new EpollServer(Calculate));
    server->InitServer();
    server->Start();

    return 0;
}